package sk.hackcraft.multibox.server;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import org.gstreamer.Gst;

public class MultiBox {
	static {
		Gst.init("MultiBoxGStreamer", new String [] { });
		(new Thread() {
			public void run() {
				Gst.main();
			}
		}).start();
	}
	
	static public void quit() {
		Gst.quit();
	}
	
	static final private Random random = new Random();
	
	static public class TokenColisionException extends Exception {
		private static final long serialVersionUID = -1680731600388583571L;

		public TokenColisionException() {
			super("There would be more than one users with same token!");
		}
	}
	
	final private Map<Long, User> users = new HashMap<Long, User>();
	final private Set<Library> rootLibraries = new HashSet<Library>();
	final public Playlist playlist = new Playlist();
	
	public synchronized User getUser(long token) {
		return users.get(token);
	}
	
	public synchronized void addUser(User user) throws TokenColisionException {
		if(users.containsKey(user.token)) {
			throw new TokenColisionException();
		}
		users.put(user.token, user);
	}
	
	public synchronized long getFreeNewToken() {
		long token;
		do {
			token = random.nextLong();
		} while(users.containsKey(token));
		
		return token;
	}
	
	public void addRootLibrary(Library library) {
		synchronized(rootLibraries) {
			rootLibraries.add(library);
		}
	}
	
	public Set<Library> getRootLibraries() {
		synchronized(rootLibraries) {
			return new HashSet<Library>(rootLibraries);
		}
	}
}
